<template>
  <div class="monitor-rule">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="left">
        <h2>监控规则管理</h2>
        <el-tag type="info" class="ml-2">共 {{ total }} 条规则</el-tag>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增规则
        </el-button>
        <el-button type="success" @click="handleImport">
          <el-icon><Upload /></el-icon>导入规则
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>导出规则
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="规则类型">
        <el-select v-model="queryParams.type" placeholder="请选择规则类型" clearable>
          <el-option
            v-for="item in ruleTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则状态">
        <el-select v-model="queryParams.status" placeholder="请选择规则状态" clearable>
          <el-option
            v-for="item in ruleStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 规则列表 -->
    <el-table
      v-loading="loading"
      :data="ruleList"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" prop="name" min-width="150" show-overflow-tooltip />
      <el-table-column label="规则类型" prop="type" width="120">
        <template #default="{ row }">
          <el-tag :type="getRuleTypeTag(row.type)">{{ getRuleTypeLabel(row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="监控目标" prop="target" min-width="150" show-overflow-tooltip />
      <el-table-column label="检查间隔" prop="interval" width="100">
        <template #default="{ row }">
          {{ row.interval }}秒
        </template>
      </el-table-column>
      <el-table-column label="阈值设置" prop="threshold" min-width="150" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button type="success" link @click="handleTest(row)">
            <el-icon><VideoPlay /></el-icon>测试
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 规则配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增规则' : '编辑规则'"
      width="700px"
      append-to-body
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择规则类型">
            <el-option
              v-for="item in ruleTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监控目标" prop="target">
          <el-input v-model="ruleForm.target" placeholder="请输入监控目标" />
        </el-form-item>
        <el-form-item label="检查间隔" prop="interval">
          <el-input-number
            v-model="ruleForm.interval"
            :min="1"
            :max="3600"
            :step="1"
          />
          <span class="ml-2">秒</span>
        </el-form-item>
        <el-form-item label="阈值设置" prop="threshold">
          <el-input
            v-model="ruleForm.threshold"
            type="textarea"
            :rows="3"
            placeholder="请输入阈值设置，例如：CPU使用率 > 80%"
          />
        </el-form-item>
        <el-form-item label="告警级别" prop="level">
          <el-select v-model="ruleForm.level" placeholder="请选择告警级别">
            <el-option
              v-for="item in alertLevels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="告警通知" prop="notify">
          <el-checkbox-group v-model="ruleForm.notify">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="webhook">Webhook</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入规则描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 规则测试对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="规则测试"
      width="600px"
      append-to-body
    >
      <div class="test-content">
        <div class="test-info">
          <h4>规则信息</h4>
          <p><strong>规则名称：</strong>{{ currentRule.name }}</p>
          <p><strong>规则类型：</strong>{{ getRuleTypeLabel(currentRule.type) }}</p>
          <p><strong>监控目标：</strong>{{ currentRule.target }}</p>
          <p><strong>阈值设置：</strong>{{ currentRule.threshold }}</p>
        </div>
        <div class="test-result" v-if="testResult">
          <h4>测试结果</h4>
          <el-result
            :icon="testResult.success ? 'success' : 'error'"
            :title="testResult.success ? '测试通过' : '测试失败'"
            :sub-title="testResult.message"
          >
            <template #extra>
              <el-button type="primary" @click="handleTest">重新测试</el-button>
            </template>
          </el-result>
        </div>
        <div class="test-action" v-else>
          <el-button type="primary" @click="handleTest" :loading="testing">
            开始测试
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Search,
  Refresh,
  Upload,
  Download,
  VideoPlay
} from '@element-plus/icons-vue'
import {
  getMonitorRules,
  addMonitorRule,
  updateMonitorRule,
  deleteMonitorRule,
  testMonitorRule,
  importMonitorRules,
  exportMonitorRules
} from '@/api/message'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  name: undefined
})

// 规则类型选项
const ruleTypes = [
  { label: '系统资源', value: 'system' },
  { label: '性能指标', value: 'performance' },
  { label: '业务指标', value: 'business' },
  { label: '安全指标', value: 'security' }
]

// 规则状态选项
const ruleStatus = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 告警级别选项
const alertLevels = [
  { label: '严重', value: 'critical' },
  { label: '警告', value: 'warning' },
  { label: '提示', value: 'info' }
]

// 数据列表
const loading = ref(false)
const ruleList = ref([])
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const ruleFormRef = ref()
const ruleForm = reactive({
  id: undefined,
  name: '',
  type: '',
  target: '',
  interval: 60,
  threshold: '',
  level: 'warning',
  notify: ['email'],
  description: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  target: [
    { required: true, message: '请输入监控目标', trigger: 'blur' }
  ],
  interval: [
    { required: true, message: '请输入检查间隔', trigger: 'blur' }
  ],
  threshold: [
    { required: true, message: '请输入阈值设置', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择告警级别', trigger: 'change' }
  ]
}

// 测试对话框控制
const testDialogVisible = ref(false)
const testing = ref(false)
const currentRule = ref({})
const testResult = ref(null)

// 初始化
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getMonitorRules(queryParams)
    ruleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('加载规则列表失败:', error)
    ElMessage.error('加载规则列表失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  loadData()
}

// 重置操作
const handleReset = () => {
  queryParams.type = undefined
  queryParams.status = undefined
  queryParams.name = undefined
  handleQuery()
}

// 新增规则
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(ruleForm, {
    id: undefined,
    name: '',
    type: '',
    target: '',
    interval: 60,
    threshold: '',
    level: 'warning',
    notify: ['email'],
    description: ''
  })
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(ruleForm, row)
  dialogVisible.value = true
}

// 删除规则
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该规则吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMonitorRule(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除规则失败:', error)
      ElMessage.error('删除规则失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMonitorRule(ruleForm)
          ElMessage.success('新增成功')
        } else {
          await updateMonitorRule(ruleForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('保存规则失败:', error)
        ElMessage.error('保存规则失败')
      }
    }
  })
}

// 测试规则
const handleTest = async (row) => {
  if (row) {
    currentRule.value = row
    testDialogVisible.value = true
    testResult.value = null
  }
  if (!currentRule.value.id) return
  
  testing.value = true
  try {
    const res = await testMonitorRule(currentRule.value.id)
    testResult.value = res.data
  } catch (error) {
    console.error('测试规则失败:', error)
    ElMessage.error('测试规则失败')
  } finally {
    testing.value = false
  }
}

// 导入规则
const handleImport = () => {
  // TODO: 实现规则导入功能
  ElMessage.info('规则导入功能开发中')
}

// 导出规则
const handleExport = async () => {
  try {
    await exportMonitorRules(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出规则失败:', error)
    ElMessage.error('导出规则失败')
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await updateMonitorRule({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  loadData()
}

// 工具方法
const getRuleTypeLabel = (type) => {
  const found = ruleTypes.find(item => item.value === type)
  return found ? found.label : type
}

const getRuleTypeTag = (type) => {
  const typeMap = {
    system: '',
    performance: 'success',
    business: 'warning',
    security: 'danger'
  }
  return typeMap[type] || 'info'
}
</script>

<style lang="scss" scoped>
.monitor-rule {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left {
      display: flex;
      align-items: center;
      gap: 10px;

      h2 {
        margin: 0;
        font-size: 20px;
      }
    }

    .right {
      display: flex;
      gap: 10px;
    }
  }

  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }

  .test-content {
    .test-info {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

      h4 {
        margin: 0 0 10px;
        color: #303133;
      }

      p {
        margin: 5px 0;
        color: #606266;
      }
    }

    .test-result {
      margin-top: 20px;
    }

    .test-action {
      margin-top: 20px;
      text-align: center;
    }
  }
}

.ml-2 {
  margin-left: 8px;
}
</style> 